package org.dragonnova.business.util;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

public class TokenUtils {
	public static String createToken(String userName,String sign) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("alg", "HS256");
		map.put("typ", "JWT");
		String token = JWT.create().withHeader(map)
				.withClaim("userName", userName)
				.withClaim("sign", sign).sign(Algorithm.HMAC256("secret"));
		return token;
	}

	public static String getValue(String token, String key) throws Exception {
		JWTVerifier verifier = JWT.require(Algorithm.HMAC256("secret")).build();
		DecodedJWT jwt = verifier.verify(token);
		Map<String, Claim> claims = jwt.getClaims();
		return claims.get(key).asString();
	}
	
	public static String getToken(HttpServletRequest request) throws Exception {
		Cookie[] cookies = request.getCookies();
		String token = "";
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				if ("token".equals(cookie.getName())) {
					token = cookie.getValue();
				}
			}
		}

		return token;
	}
}
